<?php
namespace app\controllers;

use app\models\UserAuth;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;
use yii\web\ServerErrorHttpException;

/**
 * Controller基类
 *
 * Class BaseController
 * @package app\controllers
 */
class BaseController extends Controller
{
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'captcha'=>[ // 显示验证码
                'class'=>'yii\captcha\CaptchaAction',
                'testLimit'=>1,
                'width'=>80,
                'height'=>30,
                'padding'=>-3,
                'minLength'=>4,
                'maxLength'=>4,
                'fixedVerifyCode'=>YII_ENV_TEST ? 'testme' : null,
            ],
            'auth' => [ // 第三方登录
                'class'=>'yii\authclient\AuthAction',
                'successCallback'=>[$this, 'oauthSuccessCallback'],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if ($this->isAjax()) {
            Yii::$app->response->format = Response::FORMAT_JSON;
        }
        return parent::beforeAction($action);
    }

    /**
     * 判断请求类型是否为POST
     * @return boolean
     */
    public function isPost()
    {
        return Yii::$app->request->isPost;
    }

    /**
     * 判断请求类型是否为AJAX
     * @return boolean
     */
    public function isAjax()
    {
        return Yii::$app->request->isAjax || isset($_REQUEST['ajax']);
    }

    /**
     * 第三方登录回调方法
     * @param \yii\authclient\ClientInterface $client
     * @return \yii\console\Response|null
     * @throws ServerErrorHttpException
     */
    public function oauthSuccessCallback($client)
    {
        $attributes = $client->getUserAttributes();
        $client_id = $client->getId();
        switch ($client_id) {
            case 'qq':
                $user_id = $attributes['id'];
                break;
            case 'taobao':
                $user_id = $attributes['taobao_user_id'];
                break;
            default:
                throw new ServerErrorHttpException('无法获取用户信息。');
        }
        /* @var $user_auth UserAuth */
        $user_auth = UserAuth::find()->where(['source'=>$client_id, 'user_id'=>$user_id])->one();
        if (empty($user_auth)) {
            $user_auth = new UserAuth();
            $user_auth->source = $client_id;
            $user_auth->user_id = $user_id;
            $user_auth->content = json_encode($attributes);
            $user_auth->save();
        }
        if ($user_auth->uid > 0) { // 自动登录
            Yii::$app->user->login($user_auth->user);
        } else {
            Yii::$app->session->set('oauth_login_auth_id', $user_auth->id);
            $content = <<<JJSS
<script>
function popupWindowRedirect(url, enforceRedirect) {
    if (window.opener && !window.opener.closed) {
        window.opener.location = url;
        window.opener.focus();
        window.close();
    } else {
        window.location = url;
    }
}
</script>
JJSS;
            Yii::$app->response->content = $content . '<button onclick="popupWindowRedirect(\'' . Url::to(['/user/identity/login']) . '\')">有账号：登录并绑定</button><br /><button onclick="popupWindowRedirect(\'' . Url::to(['/user/identity/register']) . '\')">没有账号：注册并绑定</button>';
            return Yii::$app->response;
        }
        return null;
    }
}
